package cn.com.yusong.doraemon.xxljob.config;

import java.util.List;

import cn.net.yugu.doraemon.scheduler.JobHandler;
import cn.net.yugu.doraemon.scheduler.XxlJobJobHandlerRegistry;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

/**
 * @author liujun
 * @date 2023-02-15 16:53
 */
@ConditionalOnProperty(prefix = "xxl.job", name = "state", havingValue = "true")
@Configuration
public class XxlJobAutoConfiguration {

    private static final Logger log = LoggerFactory.getLogger(XxlJobAutoConfiguration.class);

    @ConfigurationProperties(prefix = "xxl.job")
    @Bean
    public XxlJobProperties xxlJobProperties() {
        return new XxlJobProperties();
    }

    @Bean
    public XxlJobSpringExecutor xxlJobExecutor(XxlJobProperties xxlJobProperties) {
        log.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        XxlJobProperties.Admin admin = xxlJobProperties.getAdmin();
        if (admin != null) {
            xxlJobSpringExecutor.setAdminAddresses(admin.getAddresses());
        }
        xxlJobSpringExecutor.setAccessToken(xxlJobProperties.getAccessToken());
        XxlJobProperties.Executor executor = xxlJobProperties.getExecutor();
        if (executor != null) {
            xxlJobSpringExecutor.setAppname(executor.getAppname());
            xxlJobSpringExecutor.setAddress(executor.getAddress());
            xxlJobSpringExecutor.setIp(executor.getIp());
            xxlJobSpringExecutor.setPort(executor.getPort());
            xxlJobSpringExecutor.setLogPath(executor.getLogPath());
            xxlJobSpringExecutor.setLogRetentionDays(executor.getLogRetentionDays());
        }
        return xxlJobSpringExecutor;
    }

    /**
     * 针对多网卡、容器内部署等情况，可借助 "spring-cloud-commons" 提供的 "InetUtils" 组件灵活定制注册IP；
     * <p>
     * 1、引入依赖：
     * <dependency>
     * <groupId>org.springframework.cloud</groupId>
     * <artifactId>spring-cloud-commons</artifactId>
     * <version>${version}</version>
     * </dependency>
     * <p>
     * 2、配置文件，或者容器启动变量
     * spring.cloud.inetutils.preferred-networks: 'xxx.xxx.xxx.'
     * <p>
     * 3、获取IP
     * String ip_ = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
     */


    @ConditionalOnClass(XxlJobSpringExecutor.class)
    @DependsOn("xxlJobExecutor")
    @Bean(initMethod = "init")
    public XxlJobJobHandlerRegistry xxlJobJobHandlerRegistry(List<JobHandler> jobHandlers) {
        return new XxlJobJobHandlerRegistry(jobHandlers);
    }
}
